package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    //存入用户评论
    public TravelComment save(TravelComment travelComment) {
        //如果是评论的评论,就查询相关联的评论
        if (travelComment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            TravelComment comment = repository.findById(travelComment.getRefComment().getId()).get();
            travelComment.setRefComment(comment);
        }
        travelComment.setCreateTime(new Date());
        repository.save(travelComment);
        return travelComment;
    }

    public Page query(TravelCommentQuery qo) {
        Query query = new Query();

        //条件查询
        if (qo.getTravelId() != -1) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //分页条件,不要忘记减一  记得顺序要为正序!!!!
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "createTime");

        long count = template.count(query, TravelComment.class);

        query.with(pageRequest);

        List<TravelComment> list = template.find(query, TravelComment.class);

        return new PageImpl(list,pageRequest, count);
    }

    //获取评论总数
    public long getCount(Long id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(id));
        long count = template.count(query, TravelComment.class);
        return count;
    }


}
